﻿using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Models.Dto;
using DataManageSystem.Services;
using DataManageSystem.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OfficeDevicesController : ControllerBase
    {
        private readonly OfficeDevicesServices _officeDevicesService;
        private readonly ApplicationDbContext _context;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IConfiguration _config;
        private readonly UserServices userService;

        public OfficeDevicesController(
            OfficeDevicesServices officeDevicesService,
            ApplicationDbContext applicationDbContext,
            UserServices userService,
            IHttpContextAccessor httpContextAccessor,
            IConfiguration config
        )
        {
            _officeDevicesService = officeDevicesService;
            _context = applicationDbContext;
            this.userService = userService;
            this.httpContextAccessor = httpContextAccessor;
            _config = config;
        }

        [HttpPost("add")]
        public ObjectResult Add([FromBody] OfficeDeviceDevDto officeDeviceDevDto)
        {
            _officeDevicesService.Add(officeDeviceDevDto);
            return new ObjectResult(Result.Success("设备添加成功"));
        }

        [HttpGet("selectByPage")]
        public ObjectResult Get(
            int pageNum = 1,
            int pageSize = 10,
            string? deviceName = "",
            string? deviceType = "",
            string? deviceUsePersonName = "",
            string? deviceCode = ""
        )
        {
            User currentUser = TokenUtils.GetCurrentUser(httpContextAccessor, userService, _config);
            if(currentUser.Role == "用户")
            {
                deviceUsePersonName = currentUser.Name;
            }
            var res = _officeDevicesService.SelectByPage(
                pageNum,
                pageSize,
                deviceName,
                deviceType,
                deviceUsePersonName,
                deviceCode
            );
            return new ObjectResult(res);
        }

        [HttpPut("update")]
        public ObjectResult Update([FromBody] OfficeDeviceDevDto officeDeviceDevDto)
        {
            _officeDevicesService.Update(officeDeviceDevDto);
            return new ObjectResult(Result.Success("设备信息更新成功"));
        }

        [HttpDelete("delete/{id}")]
        public ObjectResult Delete(string id)
        {
            try
            {
                _officeDevicesService.Delete(id);
                return new ObjectResult(Result.Success("设备删除成功"));
            }
            catch (ServiceException ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
        }

        /// <summary>
        /// 批量导入接口
        /// </summary>
        /// <returns></returns>
        [HttpPost("import")]
        public ObjectResult import(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new ObjectResult(Result.Error("文件不能为空！"));
            }

            var officeDevices = new List<OfficeDevices>();

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var stream = new MemoryStream())
            {
                file.CopyToAsync(stream);
                using (var package = new ExcelPackage(stream))
                {
                    var worksheet = package.Workbook.Worksheets[0]; // 读取第一个Sheet
                    int rowCount = worksheet.Dimension.Rows; // 获取行数

                    for (int row = 2; row <= rowCount; row++) // 跳过表头，从第2行开始
                    {
                        officeDevices.Add(
                            new OfficeDevices
                            {
                                DeviceUsePerson = worksheet.Cells[row, 1].Text, //姓名
                                DeviceName = worksheet.Cells[row, 2].Text, //设备名称
                                DeviceCode = worksheet.Cells[row, 3].Text, //设备ID
                                DeviceBrand = worksheet.Cells[row, 4].Text, //设备品牌
                                DeviceType = string.IsNullOrWhiteSpace(worksheet.Cells[row, 5].Text)
                                    ? "显示器"
                                    : "笔记本",
                            }
                        );
                    }
                }
            }

            if (!officeDevices.Any())
            {
                return new ObjectResult(Result.Error("Excel 文件为空或格式不正确！"));
            }

            var entityList = officeDevices
                .Select(d => new OfficeDevices
                {
                    Id = Guid.NewGuid().ToString(),
                    DeviceCode = d.DeviceCode,
                    DeviceName = d.DeviceName,
                    DeviceBrand = d.DeviceBrand,
                    DeviceUsePerson = d.DeviceUsePerson,
                    DeviceType = d.DeviceType,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    DeviceStatus = "已分配",
                    DevicePhotoUrl = null,
                    DeviceUsePersonId = null,
                })
                .ToList();

            _context.OfficeDevices.AddRange(entityList);
            _context.SaveChanges();

            return new ObjectResult(Result.Success("批量导入成功"));
        }
    }
}
